<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="updateVisible"
    title="添加新测试步骤"
    width="700px"
    :before-close="handleClose"
    destroy-on-close
  >
    <div class="space-y-6">
      <!-- 步骤类型选择 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">步骤类型</label>
        <div class="grid grid-cols-3 gap-3">
          <div
            v-for="type in stepTypes"
            :key="type.key"
            class="step-type-option border rounded-lg p-3 cursor-pointer transition-all"
            :class="selectedStepType === type.key 
              ? 'border-primary bg-blue-50' 
              : 'border-gray-200 hover:border-gray-300'"
            @click="selectedStepType = type.key"
          >
            <div class="flex items-center mb-2">
              <el-icon class="text-primary mr-2" :size="18">
                <component :is="type.icon" />
              </el-icon>
              <span class="text-sm font-medium">{{ type.label }}</span>
            </div>
            <p class="text-xs text-gray-500">{{ type.description }}</p>
          </div>
        </div>
      </div>

      <!-- 步骤配置 -->
      <div 
        v-if="selectedStepType"
        class="border border-gray-200 rounded-lg p-4 bg-gray-50"
      >
        <!-- 通用配置 -->
        <div class="space-y-4">
          <!-- 步骤名称 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">步骤名称</label>
            <el-input
              v-model="stepConfig.name"
              placeholder="输入步骤名称"
              class="rounded-button"
            />
          </div>

          <!-- 动态配置区域 -->
          <component 
            :is="getConfigComponent()"
            v-model="stepConfig"
            @update="updateStepConfig"
          />

          <!-- 超时设置 -->
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">超时时间 (ms)</label>
              <el-input-number
                v-model="stepConfig.timeout"
                :min="1000"
                :max="60000"
                :step="1000"
                class="w-full"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">执行延迟 (ms)</label>
              <el-input-number
                v-model="stepConfig.delay"
                :min="0"
                :max="10000"
                :step="100"
                class="w-full"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div 
        v-else
        class="border border-gray-200 rounded-lg p-4 bg-gray-50"
      >
        <div class="text-center text-gray-500 py-8">
          <el-icon class="text-4xl mb-3"><i-ep-mouse /></el-icon>
          <p>请先选择一个步骤类型</p>
        </div>
      </div>

      <!-- 预览 -->
      <div 
        v-if="selectedStepType && stepConfig.name"
        class="border border-gray-200 rounded-lg p-4"
      >
        <div class="text-sm font-medium text-gray-700 mb-2">步骤预览</div>
        <div class="flex items-center p-3 bg-white rounded border">
          <div class="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center text-sm mr-3">
            {{ nextStepNumber }}
          </div>
          <el-icon class="mr-2 text-gray-600">
            <component :is="getStepTypeIcon()" />
          </el-icon>
          <div class="flex-1">
            <div class="font-medium">{{ stepConfig.name || '未命名步骤' }}</div>
            <div class="text-xs text-gray-500">
              {{ getStepTypeLabel() }} - {{ getPreviewText() }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="flex justify-between">
        <div>
          <el-checkbox v-model="addAnotherStep">继续添加下一步</el-checkbox>
        </div>
        <div>
          <el-button @click="handleClose">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmAdd"
            :disabled="!canAdd"
          >
            添加步骤
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useScriptStore } from '../stores/script'
import { ElMessage } from 'element-plus'
import {
  Mouse as iEpMouse,
  Link as iEpLink,
  Promotion as iEpPromotion,
  Check as iEpCheck,
  Clock as iEpClock,
  Camera as iEpCamera
} from '@element-plus/icons-vue'

// 动态组件
import NavigationConfig from './stepConfigs/NavigationConfig.vue'
import InputConfig from './stepConfigs/InputConfig.vue'
import ClickConfig from './stepConfigs/ClickConfig.vue'
import AssertionConfig from './stepConfigs/AssertionConfig.vue'
import WaitConfig from './stepConfigs/WaitConfig.vue'
import ScreenshotConfig from './stepConfigs/ScreenshotConfig.vue'

// Props & Emits
const props = defineProps({
  modelValue: Boolean
})

const emit = defineEmits(['update:modelValue', 'confirm'])

const scriptStore = useScriptStore()

// 处理 v-model
const updateVisible = (value) => {
  emit('update:modelValue', value)
}

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const selectedStepType = ref('')
const addAnotherStep = ref(false)

const stepConfig = ref({
  name: '',
  timeout: 5000,
  delay: 0
})

// 步骤类型配置
const stepTypes = [
  {
    key: 'navigation',
    label: '页面导航',
    description: '打开网页或导航到特定URL',
    icon: iEpLink
  },
  {
    key: 'input',
    label: '输入文本',
    description: '在表单字段中输入文本',
    icon: iEpPromotion
  },
  {
    key: 'click',
    label: '点击元素',
    description: '点击按钮、链接或其他元素',
    icon: iEpMouse
  },
  {
    key: 'assertion',
    label: '验证断言',
    description: '验证页面元素或状态',
    icon: iEpCheck
  },
  {
    key: 'wait',
    label: '等待',
    description: '等待元素出现或时间延迟',
    icon: iEpClock
  },
  {
    key: 'screenshot',
    label: '截图',
    description: '捕获页面或元素的截图',
    icon: iEpCamera
  }
]

// 计算属性
const nextStepNumber = computed(() => {
  return scriptStore.stepCount + 1
})

const canAdd = computed(() => {
  return selectedStepType.value !== '' && 
         stepConfig.value.name.trim() !== '' &&
         isConfigValid()
})

// 方法
const getConfigComponent = () => {
  const componentMap = {
    navigation: NavigationConfig,
    input: InputConfig,
    click: ClickConfig,
    assertion: AssertionConfig,
    wait: WaitConfig,
    screenshot: ScreenshotConfig
  }
  return componentMap[selectedStepType.value] || 'div'
}

const getStepTypeIcon = () => {
  const type = stepTypes.find(t => t.key === selectedStepType.value)
  return type ? type.icon : iEpMouse
}

const getStepTypeLabel = () => {
  const type = stepTypes.find(t => t.key === selectedStepType.value)
  return type ? type.label : '未知类型'
}

const getPreviewText = () => {
  switch (selectedStepType.value) {
    case 'navigation':
      return stepConfig.value.url || '未设置URL'
    case 'input':
      return `${stepConfig.value.selector || '未设置选择器'} → "${stepConfig.value.value || ''}"`
    case 'click':
      return stepConfig.value.selector || '未设置选择器'
    case 'assertion':
      return `${stepConfig.value.assertType || '检查'}: ${stepConfig.value.expectedValue || ''}`
    case 'wait':
      return stepConfig.value.waitType === 'element' 
        ? `等待元素: ${stepConfig.value.selector || ''}`
        : `等待时间: ${stepConfig.value.duration || 1000}ms`
    case 'screenshot':
      return `保存为: ${stepConfig.value.filename || 'screenshot'}.png`
    default:
      return '配置中...'
  }
}

const isConfigValid = () => {
  switch (selectedStepType.value) {
    case 'navigation':
      return stepConfig.value.url && stepConfig.value.url.trim() !== ''
    case 'input':
      return stepConfig.value.selector && 
             stepConfig.value.selector.trim() !== '' &&
             stepConfig.value.value !== undefined
    case 'click':
      return stepConfig.value.selector && stepConfig.value.selector.trim() !== ''
    case 'assertion':
      return stepConfig.value.selector && 
             stepConfig.value.selector.trim() !== '' &&
             stepConfig.value.assertType
    case 'wait':
      return stepConfig.value.waitType === 'element' 
        ? stepConfig.value.selector && stepConfig.value.selector.trim() !== ''
        : stepConfig.value.duration && stepConfig.value.duration > 0
    case 'screenshot':
      return stepConfig.value.filename && stepConfig.value.filename.trim() !== ''
    default:
      return false
  }
}

const updateStepConfig = (newConfig) => {
  stepConfig.value = { ...stepConfig.value, ...newConfig }
}

const confirmAdd = () => {
  if (!canAdd.value) return

  const newStep = {
    stepNumber: nextStepNumber.value,
    type: selectedStepType.value,
    description: stepConfig.value.name,
    ...stepConfig.value,
    timestamp: new Date().toISOString(),
    status: 'pending'
  }

  emit('confirm', newStep)

  if (addAnotherStep.value) {
    resetForm()
  } else {
    handleClose()
  }
}

const resetForm = () => {
  selectedStepType.value = ''
  stepConfig.value = {
    name: '',
    timeout: 5000,
    delay: 0
  }
}

const handleClose = () => {
  visible.value = false
  resetForm()
  addAnotherStep.value = false
}
</script>

<style scoped>
.step-type-option {
  transition: all 0.2s ease;
}

.step-type-option:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
